# coding:utf8
import copy

from sqlalchemy import func

from appserver import db_store
from sqlalchemy import or_
from models.entity.district_with_facility import DistrictWithFacility
from models.entity.model_base import ModelBase

"""
模块数据模型
"""
"""不要改了"""


# 设施
class Gps_device(ModelBase):
    __tablename__ = "gps_devices"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'装备名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"装备编码")
    phone_num = db_store.Column(db_store.Integer, nullable=False, unique=True ,comment=u"手机号")
    plate_num = db_store.Column(db_store.String(64), unique=True, comment=u"车牌号")
    sim_num = db_store.Column(db_store.Integer, unique=True, comment=u"SIM卡", )  # 0正常 1 异常 2弃用
    department = db_store.Column(db_store.Integer, db_store.ForeignKey('departments.id'), nullable=False,
                                    comment=u"部门id")

    def __repr__(self):
        return "<Gps_device %.2f>" % self.id

    def get_max_id(self):
        val = db_store.session.query(func.max(Gps_device.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):

        if self.id is None:
            self.id = self.get_max_id() + 1
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print("error is " + e)
            db_store.session.rollback()
            return False

    def delete(self):  # delete只做删除功能，其他功能不做
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False

    def get_dic(self):
        rdic = {}
        rdic["id"] = self.id
        rdic["name"] = self.name
        rdic["code"] = self.code
        rdic["phone_num"] = self.phone_num
        rdic["plate_num"] = self.plate_num
        rdic["sim_num"] = self.sim_num
        rdic["department"] = self.department
        # gps_device_num = len(Sensor.query.filter_by(sensor_type_id=self.id).all())
        # rdic["sensor_num"] = sensor_num
        return rdic

    @staticmethod
    def get_gps_device_all():
        return Gps_device.query.all()

    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        gps_device = Gps_device.query.filter(
            or_(Gps_device.code.like('%' + query_word + '%'), Gps_device.name.like('%' + query_word + '%'),
                Gps_device.phone_num.like('%' + query_word + '%'),
                Gps_device.department.like('%' + query_word + '%'))).all()
        for obj in gps_device:
            data.append(obj.to_dict())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp

    """
    def to_dict(self):
        rdic = {}
        # rdic["data_type"]=2
        rdic["id"] = self.id
        rdic["name"] = self.name
        rdic["code"] = self.code
        rdic["description"] = self.description
        rdic["dis_order"] = self.dis_order
        rdic["status"] = self.status
        rdic["facility_type"] = self.facility_type
        rdic["lat"] = self.lat
        rdic["lng"] = self.lng
        rdic["program"] = self.program
        rdic["icon"] = self.icon
        connector = DistrictWithFacility.query.filter_by(facility_id=self.id).first()
        if connector is not None:
            rdic["district_id"] = connector.district_id
        else:
            rdic["district_id"] = None
        return rdic

    ### 我加的方法
    def from_dict(self, rev_source):
        source = copy.deepcopy(rev_source)
        print('source', source)
        # if "parent_id" in source:
        #     source["parent_id"] = source.pop("parent_id")
        # if "level" in source:
        #     source["depth"] = source.pop("level")
        # if "children" in source:
        #     source.pop("children")
        # ******因为facility模型中没有district_id这个字段所以要pop掉
        if "district_id" in source:
            source.pop('district_id')
        for k in source:
            print('k', k)
            try:
                getattr(self, k)
                print('getattr', getattr(self, k))
            except AttributeError as e:
                print(e)
                raise RuntimeError("数据格式错误")
            setattr(self, k, source[k])
            # print('setattr',setattr(self, k, source[k]))

    @staticmethod
    def get_facility_by_id(id):
        return Facility.query.filter_by(id=id).first()

    @staticmethod
    def get_facility_by_name(name):
        return Facility.query.filter_by(name=name).first()

    @staticmethod
    def get_facility_by_code(code):
        return Facility.query.filter_by(code=code).first()

    @staticmethod
    def get_facilities_by_facility_type_id(type_id):
        return Facility.query.filter_by(facility_type=type_id).all()

    @staticmethod
    def get_facilities_by_district_id(district_id):
        connectors = DistrictWithFacility.query.filter_by(district_id=district_id).all()
        rlist = []
        for item in connectors:
            rlist.append(Facility.query.filter_by(id=item.facility_id).first())
        return rlist

    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        facilities = Facility.query.filter(
            or_(Facility.code.like('%' + query_word + '%'), Facility.name.like('%' + query_word + '%'),
                Facility.description.like('%' + query_word + '%'))).all()
        for obj in facilities:
            data.append(obj.to_dict())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp
    """
